package com.ljf.springtest.controller.api;

import com.ljf.springtest.bean.RequestMsg;
import com.ljf.springtest.bean.User;
import com.ljf.springtest.bean.UserLogin;
import com.ljf.springtest.service.UserLoginService;
import com.ljf.springtest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * it is a URL address.
 * can be controller the user login message.
 * the URl style all RestFul interface URL.
 * @version v1.0
 * @author JunfengLiu
 * @since v1.0
 * date: 2021-12-16 15:51:14
 */
@RestController
@RequestMapping("/prod-api/api")
public class UserLoginController {

    @Autowired
    private UserLoginService userLoginService;
    @Autowired
    private UserService userService;

  /**
     * setting the insert message method.
     * @param user user message.
     *
     * @return insert state message.
     */
    @PostMapping(value = "/register",headers = "application/json")
    public String addUser(@RequestBody User user){
        boolean result = userService.save(user);
        if (result){
            UserLogin userLogin = new UserLogin();
            userLogin.setUsername(user.getUserName());
            userLogin.setPassword(user.getPassword());
            result = userLoginService.save(userLogin);
            if (result){
                return "添加成功";
            }
            return "添加账号失败";
        }
        return "注册失败";
    }



    @PostMapping(value = "/login",headers = "application/json")
    public RequestMsg login(@RequestBody UserLogin userLogin){
        RequestMsg requestMsg = new RequestMsg();
        UserLogin realUserLogin = userLoginService.getById(userLogin.getUsername());
        if (realUserLogin != null){
            requestMsg.setMsg("登录成功");
            requestMsg.setCode(200);
        }else {
            requestMsg.setCode(401);
            requestMsg.setMsg("请求失败,没有权限");
        }
        return requestMsg;

    }

    /**
     * query all login account.
     * @return user list.
     */
    @GetMapping("/login/list")
    public List<UserLogin> list(){
        return userLoginService.list();
    }
}
